﻿using System.Collections.Generic;
using System.Linq;
using LeanBoard.Models;
using LeanBoard.ServiceReference1;

namespace LeanBoard
{
    class DominoStatuses
    {
        public const string ScheduledStatusKey = "Scheduled";
        public const string AnalysisStatusKey = "Analysis";
        public const string ReadyForAnalysisReviewStatusKey = "Ready for analysis review";
        public const string AnalysisReview = "Analysis review";
        public const string ReadyForDevelopment = "Ready for development";
        public const string DevelopmentStatusKey = "Development";
        public const string DevelopmentDoneStatusKey = "Ready for Code Review";
        public const string ReviewStatusKey = "Code Review";
        public const string ReviewDoneStatusKey = "Ready for Approval";
        public const string TestingStatusKey = "Testing";
        public const string DoneStatusKey = "Done";
    }

    class CSSStatuses
    {
        public const string ScheduledStatusKey = "scheduled";
        public const string AnalysisStatusKey = "analysis";
        public const string AnalysisReadyForReviewStatusKey = "analysisReadyForReview";
        public const string AnalysisReviewStatusKey = "analysisReview";
        public const string ReadyForDevelopmentStatusKey = "readyForDevelopment";
        public const string DevelopmentStatusKey = "development";
        public const string DevelopmentDoneStatusKey = "readyForCodeReview";
        public const string ReviewStatusKey = "codeReview";
        public const string ReviewDoneStatusKey = "readyForApproval";
        public const string TestingStatusKey = "testing";
        public const string DoneStatusKey = "done";
    }


    public class DataProvider : LeanBoard.IDataProvider
    {
        public DominoActionResult MoveItem(Item item)
        {
            
            eMgrWSP eMgrWsp = new eMgrWSPClient();
            string strstatus = TranslateStatus(item.Status);
            SETSTATUSResponse setstatusResponse = eMgrWsp.SETSTATUS(new SETSTATUSRequest(item.Unid, strstatus));
            string result = string.IsNullOrEmpty(setstatusResponse.SETSTATUSReturn.STATUSRESULTREASON)
                                ? "Done."
                                : setstatusResponse.SETSTATUSReturn.STATUSRESULTREASON;
            string className = setstatusResponse.SETSTATUSReturn.STATUSRESULTVALUE ? "Success" : "Failure";


            return new DominoActionResult(){Status=className,Message = result};
        }


        public DominoActionResult Assign(string itemUnid, string name, string leanStatus, string type)
        {
            //PR: Task Responsible = Handler
            //CR: Task Responsible = QA, Developers = DEVResponsible

            eMgrWSP eMgrWsp = new eMgrWSPClient();
            string strField = "DEVELOPERS";

            if (type.IndexOf("change") != -1 || type.IndexOf("analysis") != -1)
            {
                if (leanStatus == "testing")
                {
                    strField = "TASKRESPONSIBLE";
                }
                else
                {
                    strField = "DEVELOPERS";
                }
            }
            else
            {
                strField = "TASKRESPONSIBLE";
            }
            

            SETPERSONResponse setpersonResponse = eMgrWsp.SETPERSON(new SETPERSONRequest() { STRUNID = itemUnid, STRPERSON = name, STRFIELD = strField });
            return new DominoActionResult() {Status = setpersonResponse.SETPERSONReturn.ToString()};
        }


        public ItemsCollection GetItems(string team, string release, string filterAll)
        {
            /*
             * case 1: /teamname                   -> get all by teamname
             * case 2: /teamname/release           -> get all by teamname -> filter first and last column by release
             * case 3: /teamname/release/filterall -> get all by teamname and release
             */

            string stringRelease;
            if (filterAll == "filterall" && release != null) //if case 3
            {
                stringRelease = release;
            }
            else //in case 1 or case 3 
            {
                stringRelease = string.Empty;
            }

            eMgrWSP eMgrWSP = new eMgrWSPClient();
            var getdocumentsRequest = new GETDOCUMENTSRequest();
            getdocumentsRequest.STRRELEASE = stringRelease;
            getdocumentsRequest.STRTYPE = string.Empty;
            getdocumentsRequest.STRTEAM = team??string.Empty;
            GETDOCUMENTSResponse getdocumentsResponse = eMgrWSP.GETDOCUMENTS(getdocumentsRequest);

            WSPDOC[] document = getdocumentsResponse.GETDOCUMENTSReturn.DOCUMENT;

            var itemsCollection = new ItemsCollection();

            Dictionary<string, List<Item>> items = new Dictionary<string, List<Item>>();

            if (document[0] != null)
            {
                foreach (WSPDOC wspdoc in document)
                {
                    Item item = new Item()
                                    {
                                        DevResponsible = wspdoc.DEVELOPERS,
                                        Id = wspdoc.NRDOC,
                                        QaResponsible = wspdoc.TASKRESPONSIBLE,
                                        Status = wspdoc.LEANSTATUS,
                                        Title = wspdoc.TITLE,
                                        Type = wspdoc.GLOBALTYPE,
                                        Unid = wspdoc.DOCID,
                                        Priority = wspdoc.PRIORITY==0?int.MaxValue:wspdoc.PRIORITY,
                                        Team = wspdoc.TEAM,
                                        ItemType = wspdoc.DOCTYPE,
                                        Progress = wspdoc.PROGRESS,
                                        Sb = wspdoc.SBSTATUS,
                                        Release = wspdoc.RELEASE
                                    };

                    if (release != null && filterAll != "filterall" &&
                        (item.Status == DominoStatuses.DoneStatusKey ||
                        item.Status == DominoStatuses.ScheduledStatusKey ||
                        (item.Status == DominoStatuses.TestingStatusKey && item.Sb == "Done")
                        )) //in case 2, filter first and last column by release
                    {
                        if (item.Release.ToLower() != release.ToLower())
                        {
                            continue;
                        }
                    }

                    if (!items.ContainsKey(item.Status))
                        items.Add(item.Status, new List<Item>());

                    items[item.Status].Add(item);
                }
            }

            itemsCollection.Scheduled = items.ContainsKey(DominoStatuses.ScheduledStatusKey) ? items[DominoStatuses.ScheduledStatusKey] : new List<Item>();
            itemsCollection.Analysis = items.ContainsKey(DominoStatuses.AnalysisStatusKey) ? items[DominoStatuses.AnalysisStatusKey] : new List<Item>();
            itemsCollection.AnalysisReadyForReview = items.ContainsKey(DominoStatuses.ReadyForAnalysisReviewStatusKey) ? items[DominoStatuses.ReadyForAnalysisReviewStatusKey] : new List<Item>();
            itemsCollection.AnalysisReview = items.ContainsKey(DominoStatuses.AnalysisReview) ? items[DominoStatuses.AnalysisReview] : new List<Item>();
            itemsCollection.ReadyForDevelopment = items.ContainsKey(DominoStatuses.ReadyForDevelopment) ? items[DominoStatuses.ReadyForDevelopment] : new List<Item>();
            itemsCollection.Development = items.ContainsKey(DominoStatuses.DevelopmentStatusKey) ? items[DominoStatuses.DevelopmentStatusKey] : new List<Item>();
            itemsCollection.ReadyForCodeReview = items.ContainsKey(DominoStatuses.DevelopmentDoneStatusKey) ? items[DominoStatuses.DevelopmentDoneStatusKey] : new List<Item>();
            itemsCollection.CodeReview = items.ContainsKey(DominoStatuses.ReviewStatusKey) ? items[DominoStatuses.ReviewStatusKey] : new List<Item>();
            itemsCollection.ReadyForApporval = items.ContainsKey(DominoStatuses.ReviewDoneStatusKey) ? items[DominoStatuses.ReviewDoneStatusKey] : new List<Item>();
            itemsCollection.Testing = items.ContainsKey(DominoStatuses.TestingStatusKey) ? items[DominoStatuses.TestingStatusKey] : new List<Item>();
            itemsCollection.Done = items.ContainsKey(DominoStatuses.DoneStatusKey) ? items[DominoStatuses.DoneStatusKey] : new List<Item>();

            itemsCollection.Scheduled = itemsCollection.Scheduled.OrderBy(x => x.Priority).ToList();
            itemsCollection.ReadyForDevelopment = itemsCollection.ReadyForDevelopment.OrderBy(x => x.Priority).ToList();

            List<Item> done = itemsCollection.Testing.Where(item => item.Sb == "Done").ToList();

            foreach (Item item in done)
            {
                itemsCollection.Testing.Remove(item);
                itemsCollection.Done.Add(item);
            }

            List<Item> failed = itemsCollection.Testing.Where(item => item.Sb == "Failed").ToList();

            foreach (Item item in failed)
            {
                itemsCollection.Testing.Remove(item);
                itemsCollection.Failed.Add(item);
            }

            itemsCollection.TeamName = team;
            itemsCollection.ReleaseDate = release;

            //XmlSerializer xmlSerializer = new XmlSerializer(typeof(ItemsCollection),new Type[]{typeof(Item), typeof(List<Item>),typeof(List<Item>)});
            //using (TextWriter txt = new StreamWriter("data.xml"))
            //{
            //    xmlSerializer.Serialize(txt, itemsCollection);
            //}

            return itemsCollection;
        }


        private static string TranslateStatus(string inputStatus)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            dict.Add(CSSStatuses.ScheduledStatusKey, DominoStatuses.ScheduledStatusKey);
            dict.Add(CSSStatuses.AnalysisStatusKey, DominoStatuses.AnalysisStatusKey);
            dict.Add(CSSStatuses.AnalysisReadyForReviewStatusKey, DominoStatuses.ReadyForAnalysisReviewStatusKey);
            dict.Add(CSSStatuses.AnalysisReviewStatusKey, DominoStatuses.AnalysisReview);
            dict.Add(CSSStatuses.ReadyForDevelopmentStatusKey, DominoStatuses.ReadyForDevelopment);
            dict.Add(CSSStatuses.DevelopmentStatusKey, DominoStatuses.DevelopmentStatusKey);
            dict.Add(CSSStatuses.DevelopmentDoneStatusKey, DominoStatuses.DevelopmentDoneStatusKey);
            dict.Add(CSSStatuses.ReviewStatusKey, DominoStatuses.ReviewStatusKey);
            dict.Add(CSSStatuses.ReviewDoneStatusKey, DominoStatuses.ReviewDoneStatusKey);
            dict.Add(CSSStatuses.TestingStatusKey, DominoStatuses.TestingStatusKey);
            dict.Add(CSSStatuses.DoneStatusKey, DominoStatuses.DoneStatusKey);

            return dict[inputStatus];
        }
    }
}
